package com.prd.common.baseMapper;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.prd.common.constant.ResultCodeConstants;
import com.prd.common.converter.ExceptionConverter;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.util.HashMap;
import java.util.Map;

/**
 * api 层返回的结果
 * 
 * @author xqf
 *
 */
@JsonIgnoreProperties(value={ "success" }, allowGetters=true)
public class ApiResult {
	private Object data;

	private Integer code;

	private String message;

	public ApiResult() {
	}

	public static ApiResult success() {
		ApiResult apiResult = new ApiResult();
		apiResult.setCode(ResultCodeConstants.SUCCESS);
		return apiResult;
	}

	public static ApiResult success( Object data) {
		ApiResult apiResult = new ApiResult();
		apiResult.setCode(ResultCodeConstants.SUCCESS);
		apiResult.setData(data);
		return apiResult;
	}

	public static ApiResult error() {
		ApiResult apiResult = new ApiResult();
		apiResult.setCode(ResultCodeConstants.FAIL);
		return apiResult;
	}
	public static ApiResult error(String message) {
		ApiResult apiResult = new ApiResult();
		apiResult.setMessage(message);
		apiResult.setCode(ResultCodeConstants.FAIL);
		return apiResult;
	}

	public static ApiResult error(String message, Object data) {
		ApiResult apiResult = new ApiResult();
		apiResult.setMessage(message);
		apiResult.setData(data);
		apiResult.setCode(ResultCodeConstants.FAIL);
		return apiResult;
	}

	public ApiResult(Exception e) {
		this.code = ResultCodeConstants.FAIL;
		this.data = "";

		// 转换异常信息为提示信息
		ExceptionConverter.converter(this, e);
	}

	public ApiResult(ServiceResult ServiceResult) {
		this.data = ServiceResult == null || ServiceResult.getValue() == null ? "" : ServiceResult.getValue();
		this.code = ServiceResult == null || ServiceResult.getCode() == null ? null : ServiceResult.getCode();
		this.message = ServiceResult == null || ServiceResult.getMessage() == null ? "" : ServiceResult.getMessage();
	}

	/**
	 * 请求是否成功
	 * 
	 * @return
	 */
	public Boolean isSuccess() {
		return ResultCodeConstants.SUCCESS.equals(this.code);
	}

	

	public Object getData() {
		return data;
	}

	public String getMessage() {
		return message;
	}

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public ApiResult setData(Object data) {
		this.data = data;
		return this;
	}

	public ApiResult setMessage(String message) {
		this.message = message;
		return this;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ApiResult put(String key, Object value) {
		if (data == null || data == "") {
			data = new HashMap();
		} else {
			if (!(data instanceof Map)) {
				return this;
			}
		}

		((Map) data).put(key, value);

		return this;
	}
	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE );
	}
}
